package com.hotel.domain.service.impl;

import com.github.pagehelper.PageHelper;
import com.hotel.common.PageEntity;
import com.hotel.domain.dao.RecordInfoMapper;
import com.hotel.domain.dao.RecordMapper;
import com.hotel.domain.dao.RoomMapper;
import com.hotel.domain.service.GuestsService;
import com.hotel.domain.service.RecordInfoService;
import com.hotel.pojo.Guests;
import com.hotel.pojo.Record;
import com.hotel.pojo.RecordInfo;
import com.hotel.pojo.Room;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class RecordInfoServiceImpl implements RecordInfoService {

    @Autowired
    private RecordInfoMapper recordInfoMapper;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private GuestsService guestsService;
    @Autowired
    private RoomMapper roomMapper;

    @Override
    public PageEntity<RecordInfo> getRecordInfoList(RecordInfo recordInfo, int page, int perPage) {
        PageHelper.startPage(page,perPage);
        //获取列表
        List<RecordInfo> list = recordInfoMapper.getRecordInfoList(recordInfo);
        //获得页数
        int pageTotal = (int)Math.ceil(recordInfoMapper.getRecordInfoNum(recordInfo)/(double)perPage);
        return new PageEntity<RecordInfo>(list, page, pageTotal);
    }

    @Override
    @Transactional
    public int updateRecordInfo(RecordInfo recordInfo) {
        //更新记录
        return recordMapper.updateRecord(recordInfo.getRecord());
    }

    @Override
    @Transactional
    public int checkIn(RecordInfo[] recordInfos) {
        int n = 0;
        //获取所有顾客和记录
        Guests[] guests = new Guests[recordInfos.length];
        Record[] records = new Record[recordInfos.length];
        for(int i=0; i<recordInfos.length; i++){
            guests[i] = recordInfos[i].getGuests();
            records[i] = recordInfos[i].getRecord();
        }
        //插入顾客
        for (int i=0; i<guests.length; i++){
            n += guestsService.addGuests(guests[i]);
        }
        //设置顾客ID
        for(int i=0; i<records.length; i++){
            records[i].setGuestId(guests[i].getGuestId());
        }
        //插入记录
        for(int i=0; i<records.length; i++){
            n += recordMapper.addRecord(records[i]);
        }
        //修改房间状态
        for(int i=0; i<recordInfos.length; i++){
            Room room = new Room();
            room.setRoomId(recordInfos[i].getRoomId());
            room.setRoomStatus("已入住");
            n += roomMapper.updateRoom(room);
        }
        return n;
    }

}
